import { Router, RouteRecordRaw } from "vue-router";
import store from "@/store/index";
import { asyncRoutes } from "./data";
import { addAsyncRoute } from "@/router/utils";
import MicroAppAction from "@/utils/microAppAction";
// 判断当前权限路由是否已经初始化了
let hasRole = false;
export default function InitRouter(router: Router) {
  // 如果作为微应用运行 则不劫持路由 防止与主应用的路由冲突
  if (window.__POWERED_BY_QIANKUN__) {
    MicroAppAction.onGlobalStateChange((state: any, prev: any) => {
      console.log("子应用接收到全局状态变更信息", state, prev);
      // 动态添加缓存
      store.dispatch("INIT_CACHEPAGE_LISTACTION", state.cachePageList);
      console.log("子应用的缓存列表", store.state.cachePageList);
      store.dispatch("CHANGE_CURRENTPATH_ACTION", state.currentPath);
    });
  } else {
    router.beforeEach(async (to, from, next) => {
      // 微应用
      if (window.sessionStorage.getItem("token")) {
        // 单独运行
        // 发送http请求 获取权限菜单
        if (!hasRole) {
          // 此处模拟用写死的数据代替后端返回的数据
          const addRoutes = addAsyncRoute(asyncRoutes);
          addRoutes.forEach((t: RouteRecordRaw) => router.addRoute(t));
          hasRole = true;
          router.push(to.path);
        } else {
          // 动态添加缓存
          if (to.name && !store.state.cachePageList.includes(to.name)) {
            await store.dispatch("SET_CACHEPAGE_LISTACTION", to.name);
          }
        }
        next();
      } else {
        // 此处没有权限跳转到登陆页面
        if (!hasRole) {
          // 此处模拟用写死的数据代替后端返回的数据
          const addRoutes = addAsyncRoute(asyncRoutes);
          addRoutes.forEach((t: RouteRecordRaw) => router.addRoute(t));
          hasRole = true;
          router.push(to.path);
        } else {
          // 动态添加缓存
          if (to.name && !store.state.cachePageList.includes(to.name)) {
            await store.dispatch("SET_CACHEPAGE_LISTACTION", to.name);
          }
        }
        next();
      }
    });
    router.afterEach(() => {
      console.log("子应用路由守卫结束");
    });
  }
}
